const Koa = require('koa');

const app = new Koa()

app.use(async(ctx) => {
    // ctx.method 获取请求的方式GET/post
    if (ctx.url === '/' && ctx.method === 'GET') {
        let html = `
            <h1>Koa2 request post demo</h1>
            <form method="POST"  action="/">
                <p>userName</p>
                <input name="userName" /> <br/>
                <p>age</p>
                <input name="age" /> <br/>
                <p>webSite</p>
                <input name='webSite' /><br/>
                <button type="submit">submit</button>
            </form>
        `;
        ctx.body = html
    } else if (ctx.url === '/' && ctx.method === 'POST') {
        // ctx.body = '接收到请求'
        ctx.body = await parsePostData(ctx)
    } else {
        ctx.body = `<h1>404</h1>`
    }

});

function parsePostData(ctx) { // 获取post值
    return new Promise((resolve, reject) => {
        try {

            let postdata = ''
            // post获取值监听data有值修改变量、监听可以是on 也可以是addListener
            ctx.req.on('data', (data) => {

                postdata += data
            })

            ctx.req.on('end', function() {
                let parseData = parseQqueryStr(postdata)
                resolve(parseData);
            })
        } catch(error) {
            reject(error)
        }
    })
}

function parseQqueryStr(queryStr) {
    let queryData = {};

    let queryStrList = queryStr.split('&');
    for ( let [index, queryStr] of queryStrList.entries()) {
        let itemList = queryStr.split('=');
        queryData[itemList[0]] = decodeURIComponent(itemList[1]);;
    }

    return queryData
}
app.listen(3000, () =>{
    console.log('koa server starting demo2.js')
});
